from django.shortcuts import render

# Create your views here.

import json

from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist

from api.utils import success_response_with_data, failed_response_with_data, list_response

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action

from api.models import Animate
from api.serializers import AnimateSerializer
from api.mylogger import logger


class AnimateViewSet(viewsets.ModelViewSet):
    table_name = Animate._meta.db_table
    serializer_class = AnimateSerializer

    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['name', 'animatetype'],
                                  properties={
                                      "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
                                      "animatetype": openapi.Schema(type=openapi.TYPE_STRING, description="动作动画"),
                                      "status": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="状态(1激活，0禁用)"),
                                  }, )

    @swagger_auto_schema(operation_id='添加动画', tags=['animate'], request_body=request_body)
    @action(methods=['POST'], detail=False)
    def animate_add(self, request):
        data = json.loads(request.body.decode('utf8'))
        serializer = AnimateSerializer(data=data)
        if serializer.is_valid():
            res = serializer.save()
            res_data = {
                "table_name": self.table_name,
                "id": res.id,
            }
            return success_response_with_data(res_data, msg="新增动画成功")
        return JsonResponse(serializer.errors, status=400)

    request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
                                      required=['name', 'posetype', 'humanid'],
                                      properties={
                                          "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="内部Id"),
                                          "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
                                          "posetype": openapi.Schema(type=openapi.TYPE_STRING, description="动画类别"),
                                          "status": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="状态(1激活，0禁用)"),
                                      }, )

    @swagger_auto_schema(operation_id='修改动画', tags=['animate'],request_body=request_body_mod)
    @action(methods=['POST'], detail=False)
    def animate_mod(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        if db_id is None:
            return failed_response_with_data(msg="没有id, 修改不了")

        serializer = AnimateSerializer(data=data)
        if serializer.is_valid():
            try:
                db_ret = serializer.update(instance=Animate.objects.get(id=db_id), validated_data=data)
                res_data = {
                    "table_name": self.table_name,
                    "id": db_ret.id
                }
                return success_response_with_data(res_data, msg="修改动画成功!")
            except ObjectDoesNotExist:
                logger.debug("没有修改记录")
                return failed_response_with_data(msg=self.table_name + f"没有被修改,未发现id为{db_id}的记录")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='删除动画',  tags=['animate'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="动画表的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def animate_del(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        # qry = Material.objects.filter(id=db_id)
        # print(qry.query)
        deleted_cnt, _ = Animate.objects.filter(id=db_id).delete()
        res_data = {
            "table_name": self.table_name,
            "id": db_id,
            "rows_deleted": deleted_cnt,
            "info": "删除" + str(deleted_cnt) + "条记录!",
        }
        return success_response_with_data(res_data, msg="删除记录成功!")

    @swagger_auto_schema(operation_id='查询动画', tags=['animate'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "query": openapi.Schema(type=openapi.TYPE_STRING, description="动作名"),
            "animatetype": openapi.Schema(type=openapi.TYPE_STRING, description="动画类别"),
            "pagenum": openapi.Schema(type=openapi.TYPE_INTEGER, description="页号"),
            "pagesize": openapi.Schema(type=openapi.TYPE_INTEGER, description="记录条数"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def animate_list(self, request):
        if request.method == 'POST':
            data = json.loads(request.body.decode('utf8'))
            current_page = data.get("pagenum", 1)
            page_size = data.get("pagesize", 10)
            query = data.get("query", '')
            animatetype = data.get("animatetype", '')

        if request.method == 'GET':
            current_page = request.GET.get("pagenum", 1)
            page_size = request.GET.get("pagesize", 10)
            query = request.GET.get("query", '')
            animatetype = request.GET.get("animatetype", '')

        if current_page < 1:
            current_page = 1
        if page_size < 1:
            page_size = 10
        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = Animate.objects
            if animatetype != '':
                objects = objects.filter(animatetype=animatetype)
            if len(query):
                objects = objects.filter(name__icontains=query)
            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")
        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        serializer = AnimateSerializer(rows, many=True)

        return list_response(serializer.data, total, page_size, current_page, self.table_name)
